package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.LoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.user.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    /**
     * app用户登录
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult userLogin(LoginDto loginDto) {

        //1.判断是游客登陆还是正常登陆
        if (loginDto == null || loginDto.getPassword() == null  || loginDto.getPhone() == null) {
            //2.游客登陆：基于0号用户id生成token返回即可
            Map<String,Object> param = new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            //将token添加到集合
            param.put("token",token);

            return ResponseResult.okResult(param);
        }else {
            //3.正常登陆
            //2.1校验用户名
            ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,loginDto.getPhone()));

            if (user == null) {
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //2.1校验密码--加密加盐校验
            String password = loginDto.getPassword();
            password = MD5Utils.encode(password + user.getSalt());
            if (!password.equals(user.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //2.2校验当前用户状态
            if (user.getStatus() == 1) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
            }
            //2.3基于当前用户id生成token令牌
            String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
            Map<String,Object> param = new HashMap<>();
            //将token添加到集合
            param.put("token",token);
            param.put("user",user);

            //2.4将当前用户信息和token令牌都返回即可
            return ResponseResult.okResult(param);
        }
    }
}
